﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace EasyDLL
{
    /// <summary>
    /// 一些win32 API的声明与封装
    /// </summary>
    public class NativeAPIWrapper
    {
        #region 窗口函数

        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
        public static extern void SetForegroundWindow(IntPtr hwnd);

        [DllImport("user32.dll", EntryPoint = "GetWindow", SetLastError = true)]
        public static extern IntPtr GetWindow(IntPtr hWnd, uint wCmd);

        [DllImport("user32.dll", EntryPoint = "GetClassName", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern int GetClassName(IntPtr hWnd, StringBuilder buf, int nMaxCount);

        [DllImport("user32.dll", EntryPoint = "SetWindowPos", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern bool SetWindowPos(IntPtr hWnd, int hwndinsertAfter, int x, int y, int cx, int cy, int wFlags);

        //显示窗体（包括使得窗体最小化，最大化等等操作）
        [DllImport("user32.dll ")]
        public static extern bool ShowWindow(IntPtr hwnd, int cmdshow);

        /// <summary>
        /// 设置窗体标题
        /// </summary>
        /// <param name="hwnd">窗体句柄</param>
        /// <param name="lpStrjng">要设置的标题</param>
        /// <returns></returns>
        [DllImport("user32.dll ")]
        public static extern bool SetWindowText(IntPtr hwnd, string lpStrjng);

        /// <summary>
        /// 获得窗体的位置（相对于整个屏幕)
        /// </summary>
        /// <param name="hwnd">窗体句柄</param>
        /// <param name="rc">自定义的矩形结构，请调用该类中的RectangleEx</param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int GetWindowRect(IntPtr hwnd, ref RectangleEx rc);
        public struct RectangleEx
        {
            public int leftTopX;
            public int leftTopY;
            public int rightBottomX;
            public int rightBottomY;

            public int Width
            {
                get { return rightBottomX - leftTopX; }
            }

            public int Height
            {
                get { return rightBottomY - leftTopY; }
            }

        }

        /// <summary>
        /// 获得包含指定点的窗口的句柄
        /// </summary>
        /// <param name="p">一个被检测的点的POINT结构</param>
        /// <returns></returns>
        [DllImport("user32.dll ")]
        public static extern IntPtr WindowFromPoint(Point p);

        /// <summary>
        /// 获得窗口文字
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="lpString">用来保存文字的stringBuilder</param>
        /// <param name="nMaxCount">stringBuilder的容量</param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString,
            int nMaxCount);


        public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

        /// <summary>
        /// 枚举所有控件
        /// </summary>
        /// <param name="lpEnumFunc"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

		/// <summary>
        /// 枚举某顶层窗口的所有子窗口
        /// </summary>
        /// <param name="lpEnumFunc"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int EnumChildWindows(IntPtr hWndParent,EnumWindowsProc lpEnumFunc, IntPtr lParam);


        #endregion

        #region 消息函数

        //发送消息的类型（第二个参数）
        public const int WM_KEYDOWN = 0X100;
        public const int WM_KEYUP = 0X101;
        public const int WM_CHAR = 0X102;
        /// <summary>
        /// 发送消息，等待返回
        /// </summary>
        /// <param name="hWnd">窗体句柄</param>
        /// <param name="wMsg">被发送的消息类型(如键盘按下消息，字符消息等等)</param>
        /// <param name="wParam">附加的消息指定信息</param>
        /// <param name="lParam">附加的消息指定信息</param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern IntPtr SendMessage(
        int hWnd, // handle to destination window
        int msg, // message
        int wParam, // first message parameter
        ref COPYDATASTRUCT lParam // second message parameter
        );

        [DllImport("user32.dll", EntryPoint = "PostMessage", SetLastError = true)]
        public static extern IntPtr PostMessage(IntPtr hWnd, int wMsg, int wParam, int lParam);

        //使用COPYDATA进行跨进程通信
        public const int WM_COPYDATA = 0x004A;

        /// <summary>
        /// 给指定窗体发送消息
        /// </summary>
        /// <param name="windowReceiveTitle">接收方窗体标题名称</param>
        /// <param name="strData">要发送的数据</param>
        public static void Send(string windowReceiveTitle, string strData)
        {
            IntPtr winHandler = FindWindow(null, windowReceiveTitle);
            if (winHandler != IntPtr.Zero)
            {
                byte[] sarr = Encoding.Default.GetBytes(strData);
                int len = sarr.Length + 1;
                COPYDATASTRUCT cds;
                cds.dwData = (IntPtr)100;
                cds.lpData = strData;
                cds.cbData = len;
                SendMessage((int)winHandler, WM_COPYDATA, 0, ref cds);
            }
        }

        /// <summary>
        /// 指定窗体接收消息
        /// </summary>
        /// <example>
        /// 在窗体中覆盖接收消息函数
        /// protected override void DefWndProc(ref System.Windows.Forms.Message m)
        /// {
        ///     switch(m.Msg)
        ///     {
        ///         case WinMessageHelper.WM_COPYDATA:
        ///             string str = WinMessageHelper.Receive(ref m);
        ///             break;
        ///         default:
        ///             base.DefWndProc(ref m);
        ///             break;
        /// 
        ///     }
        /// }
        /// </example>
        /// <returns>接收的到数据</returns>
        public static string Receive(ref System.Windows.Forms.Message m)
        {
            COPYDATASTRUCT cds = new COPYDATASTRUCT();
            Type cdsType = cds.GetType();
            cds = (COPYDATASTRUCT)m.GetLParam(cdsType);
            return cds.lpData;
        }

        #endregion

        #region 鼠标函数

        [DllImport("user32.dll", EntryPoint = "SetCursorPos")]
        internal extern static int SetCursorPos(int x, int y);

        /// 使用范例：   API.mouse_event(0x2 | 0x4, x,y, 0, 0); 在（x,y）处单击一下
        public readonly int MOUSEEVENTF_LEFTDOWN = 0x2;
        public readonly int MOUSEEVENTF_LEFTUP = 0x4;
        [DllImport("user32.dll")]
        public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);


        #endregion

        #region 键盘函数


        public static int KEYEVENTF_EXTENDEDKEY = 0x0001;
        public static int KEYEVENTF_KEYUP = 0x0002;
        public static byte VK_LWIN = 0x5B;
        [DllImport("user32.dll", EntryPoint = "keybd_event")]
        public static extern void keybd_event(
            byte bVk,
            byte bScan,
            int dwFlags,
            int dwExtraInfo
        );


        #endregion

        #region 包装函数

        /// <summary>
        /// 获得窗口指定点处的句柄
        /// </summary>
        /// <param name="hwnd">主窗体句柄</param>
        /// <param name="top">该点相对于主窗体上边框的距离</param>
        /// <param name="left">该点相对于主窗体左边框的距离</param>
        /// <returns></returns>
        public static IntPtr GetWinPartFromPoint(IntPtr hwnd, int top, int left)
        {
            RectangleEx r = new RectangleEx();
            GetWindowRect(hwnd, ref r);
            //转化为整个屏幕的坐标
            int topScreen = top + r.leftTopY;
            int leftScreen = left + r.leftTopX;
            return WindowFromPoint(new Point(topScreen, leftScreen));
        }

        /// <summary>
        /// 到某处单击一下返回
        /// </summary>
        /// <param name="ox">原来的鼠标地点x</param>
        /// <param name="oy"></param>
        /// <param name="x">目标地点x</param>
        /// <param name="y"></param>
        public static void ClickPosition(int ox, int oy, int x, int y)
        {
            SetCursorPos(x, y);
            mouse_event(0x2 | 0x4, x, y, 0, 0);
            SetCursorPos(ox, oy);
        }

        #endregion
    }
}
